package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.Collections;
import java.util.List;

@DubboService
public class CommentApiImpl implements CommentApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存（可以是文字，点赞，喜欢）
     *
     * @param comment
     * @return
     */
    @Override
    public Integer save(Comment comment) {
        //查询动态
        Movement movement = mongoTemplate.findById(comment.getPublishId(), Movement.class);
        if (movement != null) {
            //向comment1对象设置被评论人属性
            comment.setPublishUserId(movement.getUserId());
        }
        //保存到数据库
        mongoTemplate.save(comment);
        //更新动态表中的对应字段，使用findAndModify()方法，查找并更新指定字段
        Query query = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", 1);
        } else if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", 1);
        } else {
            update.inc("loveCount", 1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);    //获取更新后的最新数据
        Movement modify = mongoTemplate.findAndModify(query, update, options, Movement.class);
        //获取最新评论数量并返回
        return modify.statisCount(comment.getCommentType());
    }

    /**
     * 查找动态的评论
     * @param movementId
     * @param commentType
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Comment> findComment(String movementId, CommentType commentType, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(movementId)).and("commentType").is(commentType.getType()))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        return comments;
    }

    /**
     * 根据动态id，当前操作用户id，评论的类型（点赞，喜欢）来精确判断该条数据是否存在
     * 主要作用就是判断用户是否已经对该条动态点赞或者喜欢
     * @param id
     * @param userId
     * @param commentType
     * @return
     */
    @Override
    public Boolean hasComment(String id, Long userId, CommentType commentType) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("publishId").is(new ObjectId(id))
                .and("commentType").is(commentType.getType()));
        //判断指定条件的数据是否存在
        boolean exists = mongoTemplate.exists(query, Comment.class);
        return exists;
    }



    /**
     * 删除comment数据
     * 主要用于用户取消喜欢，取消点赞后删除comment表中的数据
     * @param comment
     * @return
     */
    @Override
    public Integer remove(Comment comment) {
        //删除Comment表中的数据
        Query query = Query.query(Criteria.where("userId").is(comment.getUserId())
                .and("publishId").is(comment.getPublishId())
                .and("commentType").is(comment.getCommentType()));
        mongoTemplate.remove(query,Comment.class);
        //修改动态表中的总数量
        Query movementQuery = Query.query(Criteria.where("id").is(comment.getPublishId()));
        Update update = new Update();
        if (comment.getCommentType() == CommentType.COMMENT.getType()) {
            update.inc("commentCount", -1);
        } else if (comment.getCommentType() == CommentType.LIKE.getType()) {
            update.inc("likeCount", -1);
        } else {
            update.inc("loveCount", -1);
        }
        //设置更新参数
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);    //获取更新后的最新数据
        Movement modify = mongoTemplate.findAndModify(movementQuery, update, options, Movement.class);
        return modify.statisCount(comment.getCommentType());
    }

    /**
     * 对评论点赞，将该条评论的likeCount值加1，并返回更新后的likeCount值
     * @param commentId
     * @return
     */
    @Override
    public Integer likeComment(String commentId) {
        Query query = Query.query(Criteria.where("_id").is(commentId));
        Update update = new Update();
        update.inc("likeCount",1);
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);
        Comment comment = mongoTemplate.findAndModify(query, update, options, Comment.class);
        return comment.getLikeCount();
    }

    /**
     * 用户取消点赞，将对应的评论的likeCount值减1，并返回更新后的likeCount值
     * @param commentId
     * @return
     */
    @Override
    public Integer dislikeComment(String commentId) {
        Query query = Query.query(Criteria.where("_id").is(commentId));
        Update update = new Update();
        update.inc("likeCount",-1);
        FindAndModifyOptions options = new FindAndModifyOptions();
        options.returnNew(true);
        Comment comment = mongoTemplate.findAndModify(query, update, options, Comment.class);
        return comment.getLikeCount();
    }

    /**
     * 查询所有评论
     * @param page
     * @param pagesize
     * @param userId
     * @param comment
     * @return
     */
    @Override
    public List<Comment> findComments(Long userId,CommentType comment,Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("publishUserId").is(userId).and("commentType").is(comment.getType()))
                .skip((page - 1) * pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query, Comment.class);
    }

    /**
     * 保存小视频里的评论
     * @param comment
     */
    @Override
    public void saveVideoComments(Comment comment) {
        //设置发布人的id
        Video video = mongoTemplate.findById(comment.getPublishId(), Video.class);
        if(video!=null){
            comment.setPublishUserId(video.getUserId());
        }
        //保存
        mongoTemplate.save(comment);
        //评论数加1
        Update update = new Update();
        update.inc("commentCount",1);
        mongoTemplate.updateFirst(Query.query(Criteria.where("_id").is(video.getId())),update,Video.class);
    }

    /**
     * 查询视频的全部评论
     * @param id
     * @param comment
     * @return
     */
    @Override
    public List<Comment> findCommentByVideoId(String id, CommentType comment,Integer page,Integer pagesize) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(id)).and("commentType").is(comment.getType()))
                .skip((page-1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query, Comment.class);
    }

    /**
     * 网页端查看动态全部评论
     * @param publishId
     * @param comment
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findCommentByPage(String publishId, CommentType comment, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId)).and("commentType").is(comment.getType()));
        long count = mongoTemplate.count(query, Comment.class);
        query.skip((page - 1) * pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Comment> comments = mongoTemplate.find(query, Comment.class);
        return new PageResult(page,pagesize,count,comments);
    }
}
